from fastapi import APIRouter, HTTPException, status, Depends
from typing import List, Optional
from pydantic import BaseModel
from app.services.example_service import example_service, ExampleItem

router = APIRouter()


class ItemCreate(BaseModel):
    """创建项目的请求模型"""
    name: str
    value: float
    description: Optional[str] = None


class ItemUpdate(BaseModel):
    """更新项目的请求模型"""
    name: Optional[str] = None
    value: Optional[float] = None
    description: Optional[str] = None

@router.get("/items", response_model=List[ExampleItem])
async def get_items():
    """获取所有项目"""

    return example_service.get_all()


@router.get("/items/{item_id}", response_model=ExampleItem)
async def get_item(item_id: int):
    """根据ID获取项目"""
    try:
        return example_service.get_by_id(item_id)
    except Exception as e:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e))


@router.post("/items", response_model=ExampleItem, status_code=status.HTTP_201_CREATED)
async def create_item(item: ItemCreate):
    """创建新项目"""
    return example_service.create(
        name=item.name,
        value=item.value,
        description=item.description
    )


@router.put("/items/{item_id}", response_model=ExampleItem)
async def update_item(item_id: int, item: ItemUpdate):
    """更新项目"""
    try:
        return example_service.update(
            item_id=item_id,
            name=item.name,
            value=item.value,
            description=item.description
        )
    except Exception as e:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e))


@router.delete("/items/{item_id}", status_code=status.HTTP_204_NO_CONTENT)
async def delete_item(item_id: int):
    """删除项目"""
    try:
        example_service.delete(item_id)
    except Exception as e:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e))